package main.scala
import java.util.Arrays.ArrayList
import scala.collection.mutable.ListBuffer

object PrettyPrinter extends org.kiama.util.PrettyPrinter {

	import AST._
	
	def pretty (t : Tree) : String =
		super.pretty(show(t))
		
	def show (t : Tree) : Doc = {
	  
	//  var string : String = ""
	  
		t match {
		  case NumI(v) => text(v.toString())
		  case NumD(v) => text(v.toString())
		  case Var(name) => text(name)
		  case BAdd(l,r) => {
		    fold (prettyOfOp(l, "+", r), (_ <>_)) 
		  }
		  
		  case BSub(l,r) => {
		    fold (prettyOfOp(l, "-", r), (_ <>_)) 
		  }
		  
		  case BMul(l,r) =>{
		    fold (prettyOfOp(l, "*", r), (_ <>_)) 
		  }
		  
		  case BDiv(l,r) => {
		    fold (prettyOfOp(l, "/", r), (_ <>_)) 
		  }
		  
		  case Neg(e) =>
		  	e match {
		  	  case NumI(_) => text("-") <> show(e)
		  	  case NumD(_) => text("-") <> show(e)
		  	  case Var(_) => text("-") <> show(e)
		  	  case _ => text("-") <> parens(show(e))
		  	}
		  
		  case Add(l) => {
			  var list = new ListBuffer[Doc]
			  l.foreach(a => list += show(a)) 
			  var d : Seq[Doc] = list
			  fold (d, (_ <> text("+") <>_))
		  	}
		   
		  case Mul(l) => {
		    var list = new ListBuffer[Doc]
			l.foreach(a => list += show(a)) 
			var d : Seq[Doc] = list
			fold (d, (_ <> text("*") <>_))
		  }
		  
		  case Pow(l,r) => {
		    fold (prettyOfOp(l, "^", r), (_ <>_)) 
		  }
		  case Mod(l,r) =>  {
		    fold (prettyOfOp(l, "%", r), (_ <>_)) 
		  }
		 
		  case _ => text("") 
		}
	}
	
	/* Taken from http://code.google.com/p/kiama/source/browse/src/org/kiama/util/PrettyPrinter.scala?r=86b7088a058b4456af53c60f3a264d8bf6ab5f39*/
	private def fold (ds : Seq[Doc], f : (Doc, Doc) => Doc) =
        if (ds isEmpty)
            empty
        else
            ds.tail.foldLeft (ds.head) (f)

    private def prettyOfOp(l: Exp, op: String, r: Exp) : Seq[Doc] = {
          
           var list = new ListBuffer[Doc]
		    list += text("(")
		    list += show(l)  
		    list += text(")")
		    
		    list += text(op)
		    
		    list += text("(")
		    list += show(r)  
		    list += text(")")
		    
		    var d2 : Seq[Doc] = list
		    return d2
    }

	  
}